const PublicModel = require("@/common/public.model");


class TobaccoCrawlersModel extends PublicModel {
    /**
     * 写入烟草数据
     * @param {*} data 
     * @returns 
     */
    insertTobaccoCrawlerData(data) {
        return this.createMultiple({
            table: 'crawler_products',
            data: data,
            result: true,
            // 不需要租户信息
            isNotTenant: true
        }) 
    }

    /**
     * 查询烟草数据列表
     * @returns 
     */
    queryTobaccoDataList() {
        const SQL = `SELECT id, name, brand_name, unit, image_url, production_address, hash FROM crawler_products WHERE is_delete = 0 AND type = 3`;
        return this.query(SQL)
    }

    /**
     * 更新数据
     * @param {*} data 
     * @returns 
     */
    updateTobaccoData(data) {
        const ids = data.map(itm => `'${itm.id}'`);
        const getCaseWhen = (colName) => {
            return `
                ${colName} = CASE id
                    ${data.map(row => {
                        const v = row[colName];
                        return `WHEN '${row.id}' THEN ${typeof v === 'string' ? `'${v}'` : v }`;
                    }).join(' ')}
                END
            `
        }
        const SQL = `
            UPDATE 
                crawler_products 
            SET 
                ${getCaseWhen('name')}, 
                ${getCaseWhen('brand_name')}, 
                ${getCaseWhen('image_url')}, 
                ${getCaseWhen('reference_price')}, 
                ${getCaseWhen('hash')} 
            WHERE 
                id IN (${ids}) 
                AND is_delete = 0
        `
        return this.query(SQL);
    }

    /**
     * 创建素材
     * @param {*} data 
     * @returns 
     */
    createMaterial(data) {
        return this.createMultiple({
            table: 'product_materials',
            data: data,
            result: true
        })
    }

    /**
     * 创建多个素材文件
     * @param {*} data 
     */
    createMultipleMaterialFile(data) {
        return this.createMultiple({
            table: 'file_files',
            data: data,
            result: true
        });
    }

}

module.exports = new TobaccoCrawlersModel();